<template>
  <el-card>
    <el-row>
      <h2>根据表格数据动态生成搜索框</h2>
    </el-row>
    <el-row>
      <template v-for="(value, key, index) in query">
        <el-col :span="4" style="margin-left: 10px">
          <el-input
            v-model.trim="query[key]"
            :placeholder="`Place input ${key}`"
            :key="index"
            clearable
          ></el-input>
        </el-col>
      </template>
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-refresh" @click="handleReset"
          >重置</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="tableData">
        <template v-for="(value, key, index) in query">
          <el-table-column
            :label="key"
            :prop="key"
            :key="index"
          ></el-table-column>
        </template>
      </el-table>
    </el-row>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        {
          name: "lisi",
          category: "L",
          hh: "jj",
          kk: "kk",
        },
        {
          name: "wangwu",
          category: "K",
          hh: "xx",
          kk: "kk",
        },
        {
          name: "zhangsan",
          category: "Li",
          hh: "hh",
          kk: "kk",
        },
      ],
      tableDataClone: [],
      query: {},
      excludeQuery: ["kk"],
    };
  },
  created() {
    // 拷贝原始数据
    this.tableDataClone = JSON.parse(JSON.stringify(this.tableData));
    this.init();
  },
  methods: {
    init() {
      // 获取keys 作为 搜索的v-mode 绑定的值
      Reflect.ownKeys(this.tableDataClone[0]).forEach((key) => {
        // 要跳过的输入框
        if (!this.excludeQuery.includes(key)) {
          this.$set(this.query, key, "");
        }
      });
    },
    handleSearch() {
      // 采用过滤 做搜素功能
      this.tableData = this.tableDataClone.filter((item) =>
        this.compareObjectEq(this.query, item)
      );
    },
    handleReset() {
      // 重置 数据重新赋值，keys重新生成
      this.init();
      this.tableData = this.tableDataClone;
    },
    /**
     * 比较两个对象是否相等
     * @param {*} obj  搜索的參數 query
     * @param {*} obj2 要比較的值
     * @param {*} exclude  比对时跳过的属性
     */
    compareObjectEq(obj, obj2, exclude = []) {
      let flag = true;
      Reflect.ownKeys(obj).forEach((key) => {
        if (!exclude.includes(key)) {
          const element = obj[key];
          if (element) {
            if (!obj2[key] || !obj2[key].includes(element)) {
              flag = false;
            }
          }
        }
      });
      return flag;
    },
  },
};
</script>

<style lang="less" scoped></style>
